<template>
  <div class="container">
    <van-nav-bar title="申请配件" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <van-button class="saveBtn" type="primary" native-type="submit" @click="handleSubmit()">提交</van-button>
    <div class="publicBox formDivBox">
      <van-collapse v-model="activeName" class="collapseDiv" accordion>
        <van-collapse-item :title="`${item.name}【${item.code}】`" v-for="(item,index) in tableData" :key="index" :name="index">
          <ul class="ulBox">
            <li>
              <span>规格型号：</span>
              <b>{{ item.specifications }}【{{ item.model }}】</b>
            </li>
            <li>
              <span>图号：</span>
              <b>{{item.figureNo}}</b>
            </li>
            <li>
              <span>管理方式：</span>
              <b>{{ item.manageMould === 1 ? '批量管理' : '单件管理' }}</b>
            </li>
            <li>
              <span>条码：</span>
              <b>{{item.barCode}}</b>
            </li>
            <li>
              <span>组成数量：</span>
              <b>{{item.num}}</b>
            </li>
            <li>
              <span>更换数量：</span>
              <b>
                <van-field v-model="item.applyNum" :formatter="formatter" :max="item.num" type="number" placeholder="请输入数字" />
              </b>
            </li>
          </ul>
        </van-collapse-item>
      </van-collapse>
      <van-form ref="form">
        <van-field label="期望到货日期" name="arriveDate" :rules="[{ required: true, message: '请选择期望到货日期', trigger: 'blur' }]" v-model="ruleForm.arriveDate" size="mini" readonly @click="showTime = true" />
      </van-form>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="date" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction, getTreeMap } from '@/utils/function'
export default {
  name: 'RepairRequest',
  data() {
    return {
      activeId: null,
      activeIndex: 0,
      items: [
        {
          text: '分类1',
          id: 1,
          children: [
            { text: '分类1-1', id: 11 },
            { text: '分类1-2', id: 12 }
          ]
        },
        {
          text: '分类2',
          id: 2,
          children: [
            { text: '分类2-1', id: 21 },
            { text: '分类2-2', id: 22 }
          ]
        }
      ],
      currentDate: new Date(),
      activeName: 0,
      ruleForm: {
        type: '', // 维保类型（1->维修；2->保养）
        policyNo: '', // 维保单（维修单或保养单）
        equipId: '',
        equipPlanId: '', // 维修(保养)任务主键
        arriveDate: myFunction(new Date()).slice(0, 10),
        detailSaveList: []
      },
      show: false,
      code: localStorage.getItem('code'),
      tableData: [],
      loading: false,
      detailsObj: {},
      showTime: false
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {}
    }
  },
  created() {},
  mounted() {
    this.getData()
  },
  methods: {
    onClickNav(index) {
      this.activeIndex = index
    },
    onClickItem(data) {
      this.activeId = data.id
    },
    /** 验证检验数量只可输入大于等于0 的整数 */
    formatter(value) {
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(/[^0-9]/g, '') : 0
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(/[^0-9]/g, '') : 0
      } else {
        return 0
      }
    },
    async getData() {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '数据加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.detailsObj = this.$store.state.data
      // type 维保类型（1->维修；2->保养）
      this.ruleForm.type = this.detailsObj.type
      // 维保单（维修单或保养单）
      if (this.ruleForm.type === 1) {
        this.ruleForm.policyNo = this.detailsObj.repairNo
      } else {
        this.ruleForm.policyNo = this.detailsObj.maintainNo
      }
      this.ruleForm.equipId = this.detailsObj.equipId
      this.ruleForm.equipPlanId = this.detailsObj.id
      const res = await this.$axios.get(
        `/dobo-product/sp/bom/list?equipId=${
          this.detailsObj.equipId
        }&repairOrderId=${this.detailsObj.type === 1 ? this.detailsObj.id : ''}`
      )
      if (res.data.code === 200) {
        if (res.data.data.length < 1) {
          setTimeout(() => {
            toast.clear()
          }, 100)
          this.$dialog
            .alert({
              title: '提示',
              message: '当前数据没有可申请的配件，请去配件信息维护！'
            })
            .then(() => {
              this.$router.go(-1)
            })
          return
        } else {
          setTimeout(() => {
            toast.clear()
            this.tableData = getTreeMap(res.data.data)
            console.log(this.ruleForm)
          }, 10)
        }
      }
    },
    /* 时间选择赋值 */
    onTimeChange(value) {
      this.ruleForm.arriveDate = myFunction(value)
      this.showTime = false
    },
    handleSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          this.$dialog
            .confirm({
              title: '提示',
              message: '是否确认提交？'
            })
            .then(() => {
              this.submitApi()
            })
            .catch(() => {
              return false
            })
        })
        .catch(() => {})
    },
    submitApi() {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.tableData.forEach((item) => {
        if (item.applyNum) {
          this.ruleForm.detailSaveList.push({
            applyNum: item.applyNum,
            sparePartsId: item.sparePartsId
          })
        }
      })
      if (this.ruleForm.detailSaveList.length > 0) {
        console.log('a')
        this.$axios
          .post('/dobo-product/equip/sp/pick/pickSave', this.ruleForm)
          .then((res) => {
            if (res.data.code === 200) {
              toast.clear()
              this.$dialog
                .alert({
                  title: '提示',
                  message: '提交成功!'
                })
                .then(() => {
                  if (this.ruleForm.type === 1) {
                    this.$router.push('/internalRepair')
                  } else {
                    this.$router.push('/eqMaintain')
                  }
                })
                .catch(() => {})
            } else {
              this.$toast.fail(res.data.msg)
              setTimeout(() => {
                toast.clear()
                if (this.ruleForm.type === 1) {
                  this.$router.push('/internalRepair')
                } else {
                  this.$router.push('/eqMaintain')
                }
              }, 1000)
            }
          })
          .catch(() => {})
      } else {
        this.$toast.fail('请维护一条更换零件！')
      }
    },
    // 返回
    onClickLeft() {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        if (this.ruleForm.type === 1) {
          this.$router.push('/internalRepair')
        } else {
          this.$router.push('/eqMaintain')
        }
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .collapseDiv {
    .ulBox {
      li {
        font-size: 18px;
        padding: 5px 0;
        height: 40px;
        line-height: 40px;
        overflow: hidden;
        span {
          float: left;
          width: 100px;
        }
        b {
          width: calc(100% - 100px);
          float: left;
          font-weight: normal;
          color: #022566;
        }
      }
    }
  }
}
</style>
<style lang='scss'>
.collapseDiv {
  margin-bottom: 10px;
  .van-cell__title {
    font-size: 18px !important;
    color: #022566;
  }
  .van-field {
    border: 1px solid #ccc;
    height: 35px !important;
    line-height: 35px;
    padding: 0 10px;
    width: 200px;
  }
}
</style>
